# Create your views here.
from django.core.cache import cache
from django.http import JsonResponse
from django.views import View

from apps.areas.models import Area


class AreasView(View):
    def get(self, requset):

        province_list = cache.get("province")
        if province_list is None:
            try:
                provinces = Area.objects.filter(parent=None)

                province_list = []

                for province in provinces:
                    province_list.append({"id": province.id, "name": province.name})

                cache.set("province", province_list, 3600 * 24 * 10)
            except Exception as e:
                print(e)
                return JsonResponse({"code": 400, "errmsg": "查询失败"})
        else:
            print("使用缓存的省数据")
        return JsonResponse({"code": 0, "errmsg": "ok", "province_list": province_list})


class SubAreasView(View):
    def get(self, requset, id):

        sub_data = cache.get("sub_data")

        if sub_data is None:
            try:
                sub_area = Area.objects.get(id=id)

                sub_all = sub_area.subs.all()

                subs = []
                for sub in sub_all:
                    subs.append({"id": sub.id, "name": sub.name})

                sub_data = {
                    "id": sub_area.id,
                    "name": sub_area.name,
                    "subs": subs
                }
                cache.set("sub_data" + id, sub_data, 3600 * 24 * 10)
            except Exception as e:
                print(e)
                return JsonResponse({"code": 400, "errmsg": "查询失败"})
        else:
            print("使用缓存市")
        return JsonResponse({"code": 0, "errmsg": "ok", "sub_data": sub_data})
